<script setup lang="tsx">
import { usePagination } from '@sa/alova/client';
import { NButton, NPopconfirm, NTag } from 'naive-ui';
import type { HTMLAttributes } from 'vue';
import { reactive } from 'vue';
import PorDictTag from '@/components/_builtin/por-dict-tag/index.vue';
import useCheckedColumns from '@/hooks/common/table/table-columns';
import useTableOperate from '@/hooks/common/table/table-operate';
import { $t } from '@/locales';
import {
  batchDeleteConfig,
  batchDeleteConfigCategory,
  deleteConfig,
  deleteConfigCategory,
  paginateConfig,
  paginateConfigCategory
} from '@/service/api/manage';
import { useAppStore } from '@/store/modules/app';

import ConfigCategoryOperateDrawer from './modules/config-category-operate-drawer.vue';
import ConfigCategorySearch from './modules/config-category-search.vue';
import ConfigOperateDrawer from './modules/config-operate-drawer.vue';
import ConfigSearch from './modules/config-search.vue';

const appStore = useAppStore();

// 配置分类表
const configCategorySearchParams = reactive({
  status: null,
  keyword: ''
});

const {
  loading: configCategoryLoading,
  data: configCategoryData,
  refresh: configCategoryRefresh,
  page: configCategoryPage,
  pageSize: configCategoryPageSize,
  pageCount: configCategoryPageCount,
  send: configCategorySend,
  remove: configCategoryRemove
} = usePagination(
  (pageNum, size) =>
    paginateConfigCategory({
      ...configCategorySearchParams,
      pageNumber: pageNum,
      pageSize: size
    }),
  {
    data: ({ records }) => records,
    total: ({ total }) => total,

    // trigger reload when states in `searchParams` changed
    watchingStates: [configCategorySearchParams],

    // debounce of `searchParams`
    debounce: [500]
  }
);

const getConfigCategoryDataByPage = (newPage = 1) => {
  configCategoryPage.value = newPage;
  configCategorySend(configCategoryPage.value, configCategoryPageSize.value);
};

const {
  drawerVisible: configCategoryDrawerVisible,
  operateType: configCategoryOperateType,
  editingData: configCategoryEditingData,
  handleAdd: handleConfigCategoryAdd,
  handleEdit: handleConfigCategoryEdit,
  checkedRowKeys: checkedConfigCategoryRowKeys,
  handleDelete: handleConfigCategoryDelete,
  handleBatchDelete: handleConfigCategoryBatchDelete
  // closeDrawer
} = useTableOperate(configCategoryData, {
  async delete(row) {
    await deleteConfigCategory(row.id as number);
    configCategoryRemove(row);
  },
  async batchDelete(rows) {
    await batchDeleteConfigCategory(rows.map(({ id }) => id as number));
    configCategoryRemove(...rows);
  }
});

// 配置分类表
const { columnChecks: configCategoryColumnChecks, columns: configCategoryColumns } = useCheckedColumns<
  typeof paginateConfigCategory
>(() => [
  {
    type: 'selection',
    align: 'center',
    width: 48
  },
  {
    key: 'name',
    title: '名称',
    align: 'center',
    minWidth: 100
  },
  {
    key: 'code',
    title: '编码',
    align: 'center',
    minWidth: 100
  },
  {
    key: 'status',
    title: '状态',
    align: 'center',
    width: 100,
    render: row => {
      if (row.status === null) {
        return <NTag></NTag>;
      }

      return <PorDictTag dict-code="common_status" value={row.status}></PorDictTag>;
    }
  },
  {
    key: 'operate',
    title: '操作',
    align: 'center',
    width: 130,
    fixed: 'right',
    render: row => (
      <div class="flex-center gap-8px">
        <NButton type="primary" ghost size="small" onClick={() => editConfigCategory(row.id as number)}>
          {$t('common.edit')}
        </NButton>
        <NPopconfirm onPositiveClick={() => handleConfigCategoryDelete(row.id as number)}>
          {{
            default: () => $t('common.confirmDelete'),
            trigger: () => (
              <NButton type="error" ghost size="small">
                {$t('common.delete')}
              </NButton>
            )
          }}
        </NPopconfirm>
      </div>
    )
  }
]);

// 配置表格
const configSearchParams = reactive({
  // if you want to use the searchParams in Form, you need to define the following properties, and the value is null
  // the value can not be undefined, otherwise the property in Form will not be reactive
  status: null,
  keyword: null,
  categoryCode: '',
  categoryName: ''
});
const {
  loading: configLoading,
  data: configData,
  refresh: configRefresh,
  page: configPage,
  pageSize: configPageSize,
  pageCount: configPageCount,
  send: configSend,
  remove: configRemove
} = usePagination(
  (pageNum, size) =>
    paginateConfig({
      ...configSearchParams,
      pageNumber: pageNum,
      pageSize: size
    }),
  {
    data: ({ records }) => records,
    total: ({ total }) => total,

    // trigger reload when states in `searchParams` changed
    watchingStates: [configSearchParams],

    // debounce of `searchParams`
    debounce: [500]
  }
);
const getConfigDataByPage = (newPage = 1) => {
  configPage.value = newPage;
  configSend(configPage.value, configPageSize.value);
};

const {
  drawerVisible: configDrawerVisible,
  operateType: configOperateType,
  editingData: configEditingData,
  handleAdd: handleConfigAdd,
  handleEdit: handleConfigEdit,
  checkedRowKeys: checkedConfigRowKeys,
  handleBatchDelete: handleConfigBatchDelete,
  handleDelete: handleConfigDelete
  // closeDrawer
} = useTableOperate(configData, {
  async delete(row) {
    await deleteConfig(row.id as number);
    configRemove(row);
  },
  async batchDelete(rows) {
    await batchDeleteConfig(rows.map(({ id }) => id as number));
    configRemove(...rows);
  }
});

const { columnChecks: configColumnChecks, columns: configColumns } = useCheckedColumns<typeof paginateConfig>(() => [
  {
    type: 'selection',
    align: 'center',
    width: 48
  },
  {
    key: 'configKey',
    title: '键',
    align: 'center',
    minWidth: 100
  },
  {
    key: 'value',
    title: '值',
    align: 'center',
    minWidth: 100
  },
  {
    key: 'status',
    title: '状态',
    align: 'center',
    width: 100,
    render: row => {
      if (row.status === null) {
        return <NTag></NTag>;
      }

      return <PorDictTag dict-code="common_status" value={row.status}></PorDictTag>;
    }
  },
  {
    key: 'operate',
    title: '操作',
    align: 'center',
    width: 130,
    fixed: 'right',
    render: row => (
      <div class="flex-center gap-8px">
        <NButton type="primary" ghost size="small" onClick={() => editConfig(row.id as number)}>
          {$t('common.edit')}
        </NButton>
        <NPopconfirm onPositiveClick={() => handleConfigDelete(row.id as number)}>
          {{
            default: () => $t('common.confirmDelete'),
            trigger: () => (
              <NButton type="error" ghost size="small">
                {$t('common.delete')}
              </NButton>
            )
          }}
        </NPopconfirm>
      </div>
    )
  }
]);

function editConfig(id: number) {
  handleConfigEdit(id);
}

// 配置类别表格操作
function handleConfigCategoryRowProps(row: Api.Manage.ConfigCategory): HTMLAttributes {
  return {
    onClick: () => {
      configSearchParams.categoryCode = row.code;
      configSearchParams.categoryName = row.name;
      getConfigDataByPage();
    }
  };
}

function editConfigCategory(id: number) {
  handleConfigCategoryEdit(id);
}
</script>

<template>
  <NSplit :size="0.4" pane1-class="pr-2" pane2-class="pl-2" :resize-trigger-size="0">
    <template #1>
      <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
        <ConfigCategorySearch v-model:model="configCategorySearchParams" @search="getConfigCategoryDataByPage" />
        <NCard title="配置类别" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
          <template #header-extra>
            <TableHeaderOperation
              v-model:columns="configCategoryColumnChecks"
              :disabled-delete="checkedConfigCategoryRowKeys.length === 0"
              :loading="configCategoryLoading"
              @add="handleConfigCategoryAdd"
              @delete="handleConfigCategoryBatchDelete"
              @refresh="configCategoryRefresh"
            />
          </template>
          <NDataTable
            v-model:checked-row-keys="checkedConfigCategoryRowKeys"
            :columns="configCategoryColumns"
            :data="configCategoryData"
            size="small"
            :loading="configCategoryLoading"
            remote
            :row-key="row => row.id"
            :pagination="{
              page: configCategoryPage,
              pageSize: configCategoryPageSize,
              showSizePicker: true,
              pageCount: configCategoryPageCount,
              pageSizes: [10, 15, 20, 25, 30],
              onUpdatePage(value) {
                configCategoryPage = value;
              },
              onUpdatePageSize(value) {
                configCategoryPageSize = value;
              }
            }"
            :scroll-x="600"
            class="sm:h-full"
            min-height="350px"
            :flex-height="!appStore.isMobile"
            :row-props="handleConfigCategoryRowProps"
          />
        </NCard>
        <ConfigCategoryOperateDrawer
          v-model:visible="configCategoryDrawerVisible"
          :operate-type="configCategoryOperateType"
          :row-data="configCategoryEditingData"
          @submitted="configCategoryRefresh"
        />
      </div>
    </template>
    <template #2>
      <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
        <ConfigSearch v-model:model="configSearchParams" @search="getConfigDataByPage" />
        <NCard title="配置列表" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
          <template #header-extra>
            <TableHeaderOperation
              v-model:columns="configColumnChecks"
              :disabled-delete="checkedConfigRowKeys.length === 0"
              :hide-delete="true"
              :loading="configLoading"
              @add="handleConfigAdd"
              @delete="handleConfigBatchDelete"
              @refresh="configRefresh"
            />
          </template>
          <NDataTable
            v-model:checked-row-keys="checkedConfigRowKeys"
            :columns="configColumns"
            :data="configData"
            size="small"
            :scroll-x="600"
            :loading="configLoading"
            remote
            :row-key="row => row.id"
            :pagination="{
              page: configPage,
              pageSize: configPageSize,
              showSizePicker: true,
              pageCount: configPageCount,
              pageSizes: [10, 15, 20, 25, 30],
              onUpdatePage(value) {
                configPage = value;
              },
              onUpdatePageSize(value) {
                configPageSize = value;
              }
            }"
            class="sm:h-full"
            min-height="350px"
            :flex-height="!appStore.isMobile"
          />
          <ConfigOperateDrawer
            v-model:visible="configDrawerVisible"
            :operate-type="configOperateType"
            :row-data="configEditingData"
            :category-code="configSearchParams.categoryCode"
            @submitted="configRefresh"
          />
        </NCard>
      </div>
    </template>
  </NSplit>
</template>

<style scoped></style>
